<script setup lang="tsx">
import { ref } from 'vue';
import { $t } from '@/locales';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import OperateModal from './modules/operate-modal.vue';
import Search from './modules/search.vue';
import { SysemailsendconfigApi } from '@/api-services/apis/sysemailsendconfig-api';
import { ApiSysSensitiveWordOut, ApiSysSensitiveWordQuery } from '@/api-services';
import { SyssensitivewordApi } from '@/api-services/apis/syssensitiveword-api';
import { Tag } from '@visactor/vue-vtable';
import { ElTag, ElButton, ElPopconfirm } from 'element-plus';
//import Button from 'element-plus/es/components/button';
//import Popconfirm from 'element-plus/es/components/popconfirm';

const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysSensitiveWordQuery) =>
  fetchTableQuery<ApiSysSensitiveWordQuery, ApiSysSensitiveWordOut>(params,
    (internalParams: ApiSysSensitiveWordQuery) =>
      getAPI(SyssensitivewordApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});
const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: '',
    startDate:undefined,
    endDate:undefined
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 230,
    },
    //敏感词内容
    {
      prop: 'word',
      //dataIndex: 'word',
      label: $t('page.sensitiveWord.word'),
      minWidth: 230,
    },
    //分类
    {
      prop: 'category',
      //dataIndex: 'category',
      label: $t('page.sensitiveWord.category'),
      minWidth: 230,
    },
    {
      prop: 'isEnable',
      label: $t('page.manage.common.isEnable'),
      align: 'center',
      minWidth: 80,
      formatter: record => {
        if (record.isEnable === null) {
          return '';
        }
        const label = $t(record.isEnable ? 'page.manage.common.status.enable' : 'page.manage.common.status.disable');
        const color = record.isEnable ? 'success' : 'warning'

        return <ElTag type={color}> {label} </ElTag>;
      }
    },

    {
      prop: 'remark',
      //dataIndex: 'remark',
      label: $t('page.manage.common.remark'),
      minWidth: 230,
    },
    //匹配模式
    {
      prop: 'matchMode',
      //dataIndex: 'matchMode',
      label: $t('page.sensitiveWord.matchMode'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        const tagMap: Record<number, string> = {
          //精确匹配
          0: $t('page.sensitiveWord.matchModeEnum.full'),
          //模糊匹配
          1: $t('page.sensitiveWord.matchModeEnum.contains')
        };

        switch (record.matchMode) {
          case 0:
            return <ElTag type="primary">{tagMap[record.matchMode]}</ElTag>;
          case 1:
            return <ElTag type="success">{tagMap[record.matchMode]}</ElTag>;
          default:
            return '';
        }

      }

    },
    {
      //敏感词等级
      prop: 'severityLevel',
      //dataIndex: 'severityLevel',
      label: $t('page.sensitiveWord.severityLevel'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        const tagMap: Record<number, string> = {
          1: $t('page.sensitiveWord.severityLevelEnum.low'),
          2: $t('page.sensitiveWord.severityLevelEnum.medium'),
          3: $t('page.sensitiveWord.severityLevelEnum.high'),
        };

        switch (record.severityLevel) {
          case 1:
            return <ElTag type="primary">{tagMap[record.severityLevel]}</ElTag>
          case 2:
            return <ElTag type="warning">{tagMap[record.severityLevel]}</ElTag>
          case 3:
            return <ElTag type="danger">{tagMap[record.severityLevel]}</ElTag>

          default:
            return '';
        }
      }
    },

    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //创建人
      prop: 'creatorUserName',
      //dataIndex: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //修改时间
      prop: 'updateTime',
      //dataIndex: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //修改人
      prop: 'updateUserName',
      //dataIndex: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      fixed: 'right',
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id!)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>

        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  editingId,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  //rowSelection,
  onBatchDeleted,
  onDeleted

} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const handleDelete = async (id: number) => {
  const ids = [];

  // 提交请求
  const [err, res] = await feature(getAPI(SyssensitivewordApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  if (checkedRowKeys.value == undefined || checkedRowKeys.value.length == 0) {
    return;
  }
  const ids = checkedRowKeys.value.join(',');

  // 提交请求
  const [err, res] = await feature(getAPI(SyssensitivewordApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>

    <ElCard :title="$t('page.sensitiveWord.titleList')" :bordered="false" :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper" size="small">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.sensitiveWord.titleList') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="handleAdd"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :edit-id="editingId"
        @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
